window.onkeydown = keydownControl;
window.onkeyup = keyupControl;
$('#new_game').click(function () { 
	if (!playing) {
		startGame();
	}
	else {
		if (playing) {
			restore();
			startGame();
		}
	}
    
  });

var keys = [37, 38, 39, 40];

function preventDefault(e) {
  e = e || window.event;
  if (e.preventDefault)
      e.preventDefault();
  e.returnValue = false;  
}

function keydown(e) {
    for (var i = keys.length; i--;) {
        if (e.keyCode === keys[i]) {
            preventDefault(e);
            return;
        }
    }
}

function wheel(e) {
  preventDefault(e);
}

function disable_scroll() {
  if (window.addEventListener) {
      window.addEventListener('DOMMouseScroll', wheel, false);
  }
  window.onmousewheel = document.onmousewheel = wheel;
  document.onkeydown = keydown;
}

function enable_scroll() {
    if (window.removeEventListener) {
        window.removeEventListener('DOMMouseScroll', wheel, false);
    }
    window.onmousewheel = document.onmousewheel = document.onkeydown = null;  
}

function showKilledLoisModal() {
	TINY.box.show({image:'images/stewie-won.jpg',boxid:'frameless',animate:true,openjs:function(){alert('congrats, you killed lois!')}})
}

function startGame() {
	// start the chase music if sound is enabled on new game click
	if ($("#enable-sound:checked").val() !== undefined) {
		chase = new Audio("sound/chase.mp3");
		chase.play();
	}
	// generate our maze(not my code)
	mazeResult = maze(numberOfRows, numberOfColumns); // return an object containing the maze representation
	horiz = mazeResult.horiz;
	verti = mazeResult.verti;
	// draws the maze from the representational two 2-dimensional arrays we generated
	drawMaze(); 
	
	// we are now playing
	playing = true;
	disable_scroll();
}

// we call this function after the game has ended to set parameters to their initial values before starting a new game
function initParameters() {
	currentStewieX = cellDimentions * (numberOfColumns - 1) + 2;
	currentStewieY = cellDimentions * (numberOfRows - 2) + 2;
	up = false;
	down = false;
	right = false;
	left = true;
	currentShotX = 0;
	currentShotY = 0;
	dx=0;
	dy=0;
	dxshot=0;
	dyshot=0;
	timeLeft = 60;
	numberOfShotsLeft = 5;
	$("#shots-left").text(numberOfShotsLeft);
	$("#time-left").text(timeLeft);
	playing = false;
}

//this function whenever any key is pressed
function keydownControl(e) {
	// user want to shoot
	if (e.ctrlKey) {
		// if he is not playing, he cant shoot
		if (playing) {
		shotFired = true;
		numberOfShotsLeft -= 1;
		// if he has no more shots left, he cant shoot
		if (numberOfShotsLeft >= 0) {
			$("#shots-left").text(numberOfShotsLeft);
			if ($("#enable-sound:checked").val() !== undefined) {
				lazer = new Audio("sound/lazer.mp3");
				lazer.play();
		}
		
		// this is kind of a mess to read
		// basically i just calculate here the starting point of our shot(lazer) and set the dx of the shot so it will move
		// i know in witch direction the shot is suppose to go because of the left,right, up, down variables
		var distanceFromWallX = currentStewieX % cellDimentions;
		var distanceFromWallY = currentStewieY % cellDimentions;
		var TopLeftCellCorner = {x: currentStewieX - distanceFromWallX,y: currentStewieY - distanceFromWallY};
		
		if (left) {
			dxshot = -2;
			currentShotX = TopLeftCellCorner.x - horizontalShotWidth;
			currentShotY = TopLeftCellCorner.y + 12;
			drawHorizontalShot();
		}
		if (right) {
			dxshot = 2;
			currentShotX = TopLeftCellCorner.x + cellDimentions;
			currentShotY = TopLeftCellCorner.y + 12;
			drawHorizontalShot();
		}
		if (up) {
			dyshot = -2;
			currentShotX = TopLeftCellCorner.x + 12;
			currentShotY = TopLeftCellCorner.y - verticalShotHeight;
			drawVerticalShot();
		}
		if (down) {
			dyshot = 2;
			currentShotX = TopLeftCellCorner.x + 12;
			currentShotY = TopLeftCellCorner.y + cellDimentions;
			drawVerticalShot();
		}
		}
		}
	}
	
	// a press on the arrows of the keyboard
	// manipulates the dx of stewie, that is, where he should go next
	if(e.keyCode==37) {
		up = false;
		down = false;
		left = true;
		right = false;
		dx = -1;
		dy = 0;
	}
	else if(e.keyCode==38) {
		left = false;
		right = false;
		up = true;
		down = false;
		dx = 0;
		dy = -1;
	}
	else if(e.keyCode==39) {
		up = false;
		down = false;
		right = true;
		left = false;
		dx = 1;
		dy = 0;
	}
	else if(e.keyCode==40) {
		down = true;
		up = false;
		left = false;
		right = false;
		dx = 0;
		dy = 1;
	}
	else if (e.keyCode==78) {
		$('#new_game').click();
	}
}

//this function whenever any key is released
function keyupControl(e) {
	// if a user releases, stewie stops
	dx = 0;
	dy = 0;
}
 
//this function is called repeatedly at an interval of 15ms
function moveStewie() {
	
	var distanceFromWall;
	
	// we first clear stewie from our canvas(so as to draw him in another location
	clearStewie();
	// if nothing is pressed just draw him again(did nothing)
	if ((dx == 0) && (dy ==0)) {
		drawStewie();
		return;
	}
	
	// calculate the location of stewie (along with his dimentions)
	var TopLeft = {x: currentStewieX,y: currentStewieY};
	var TopRight = {x: currentStewieX + stewieWidth,y: currentStewieY};
	var BottomLeft = {x: currentStewieX,y: currentStewieY + stewieHeight};
	var BottomRight = {x: currentStewieX + stewieWidth,y: currentStewieY + stewieHeight};
	
	// if he hits any of the walls, draw him(he cant go through the wall)
	if ((BottomLeft.x + dx) == 0) {
		drawStewie();
		return;
	}
	if ((TopRight.x + dx) == canvas.width) {
		drawStewie();
		return;
	}
	if ((BottomRight.y + dy) == canvas.height) {
		drawStewie();
		return;
	}
	if ((TopLeft.y + dy) == 0) {
		drawStewie();
		return;
	}
	
	// if the fron end and the back end of stewie are not in the same cell, he cannot move verticaly
	if ( (TopRight.x % cellDimentions) != ((TopLeft.x % cellDimentions) + stewieWidth)) dy = 0;
	// if the lower end and the upper end of stewie are not in the same cell, he cannot move horizontaly
	if ( ((TopLeft.y % cellDimentions) + stewieHeight) != ((TopLeft.y + stewieHeight) % cellDimentions)) dx = 0;
	
	// check if there is wall in the direction he is going, if so, stop him(dx = 0)
	if (dx > 0) {
		distanceFromWall = TopRight.y % cellDimentions;
		var x1 = ((TopRight.x + dx) / cellDimentions) - 1;
		var y1 = (TopRight.y - distanceFromWall) / cellDimentions;
		if ((x1 % 1) == 0) {
			if (horiz[y1][x1] != 1) dx = 0;
		}

	}
	
	// same thing, but here check if he reached lois, he cannot reach her from the right
	if (dx < 0) {
		distanceFromWall = TopLeft.y % cellDimentions;
		var x1 = ((TopLeft.x + dx) / cellDimentions) - 1;
		var y1 = (TopLeft.y - distanceFromWall) / cellDimentions;
		if (x1 == 1 && y1 == 0) {
			if ($("#enable-sound:checked").val() !== undefined) {
				victoryIsMine = new Audio("sound/victory.mp3");
				victoryIsMine.play();
			}
			endGame();
			restore();
			return;
		} 
		if ((x1 % 1) == 0) {
			if (horiz[y1][x1] != 1) dx = 0;
		}
		
	}
	// check if there is wall in the direction he is going, if so, stop him(dy = 0)
	if (dy > 0) {
		distanceFromWall = BottomLeft.x % cellDimentions;
		var x1 = ((BottomLeft.x - distanceFromWall) / cellDimentions) ;
		var y1 = (BottomLeft.y + dy) / cellDimentions;
		if ((y1 % 1) == 0) {
			if (verti[y1 - 1][x1] != 1) dy = 0;
		}
	}
	
	// same thing, but here check if he reached lois, he cannot reach her from up
	if (dy < 0) {
		distanceFromWall = TopLeft.x % cellDimentions;
		var x1 = ((TopLeft.x - distanceFromWall) / cellDimentions) ;
		var y1 = (TopLeft.y + dy) / cellDimentions;
		if (x1 == 0 && y1 == 1) {
			if ($("#enable-sound:checked").val() !== undefined) {
				victoryIsMine = new Audio("sound/victory.mp3");
				victoryIsMine.play();
			}
			endGame();
			restore();
			return;
		}
		if ((y1 % 1) == 0) {
			if (verti[y1 - 1][x1] != 1) dy = 0;
		}
		
	}
	
	// translate stewie
	currentStewieX += dx;
	currentStewieY += dy;
	
	// draw him in different directions(depending on the direction he just walked in)
	// each direction is another image(same image just rotated)
	if (dx != 0) {
		drawStewie();
	}
	if (dy < 0) {
		drawStewie('U');
	}
	if (dy > 0) {
		drawStewie('D');
	}
}

// this moves the shot fired, same logic as with stewie, except the shot keeps on going even there is no key pressed
function moveShot() {
	
	var x1;
	var y1;
	var wall = false;
	var canvasEnd = 0;
	
	var distanceFromWallX = currentStewieX % cellDimentions;
	var distanceFromWallY = currentStewieY % cellDimentions;
	var TopLeftCellCorner = {x: currentStewieX - distanceFromWallX,y: currentStewieY - distanceFromWallY};
	
	if (shotFired) {
	if (left) {
		x1 = (currentShotX + horizontalShotWidth + dxshot) / cellDimentions ;
		y1 = (currentShotY - 12) / cellDimentions;
		if (x1 == 1 && y1 == 0) {
			if ($("#enable-sound:checked").val() !== undefined) {
				victoryIsMine = new Audio("sound/victory.mp3");
				victoryIsMine.play();
			}
			endGame();
			restore();
			return;
		} 
		if ((x1 % 1) == 0) {
			if (horiz[y1][x1 - 1] != 1) wall = true;
		}
		clearHorizontalShot();
		canvasEnd = ((currentShotX + dxshot) == 0);
		if (canvasEnd || wall) {
			if (wall && !canvasEnd) {
				horiz[y1][x1 - 1] = 1;
				eraseVerticalWall(x1,y1);
				if ($("#enable-sound:checked").val() !== undefined) {
					explosion = new Audio("sound/explosion.wav");
					explosion.play();
				}
			}
			currentShotX = TopLeftCellCorner.x - horizontalShotWidth;
			currentShotY = TopLeftCellCorner.y + 12;
			dxshot = 0;
			dyshot = 0;
			return;
		}
		if (dxshot != 0) {
			currentShotX += dxshot;
			currentShotY += 0;
			drawHorizontalShot();
		}
	}
	
	if (right) {
		x1 = (currentShotX + dxshot) / cellDimentions;
		y1 = (currentShotY - 12) / cellDimentions;
		if ((x1 % 1) == 0) {
			if (horiz[y1][x1 - 1] != 1) wall = true;
		}
		clearHorizontalShot();
		canvasEnd = (currentShotX + horizontalShotWidth + dxshot) == canvas.width;
		if (canvasEnd || wall) {
			if (wall && !canvasEnd) {
				horiz[y1][x1 - 1] = 1;
				eraseVerticalWall(x1,y1);
				if ($("#enable-sound:checked").val() !== undefined) {
					explosion = new Audio("sound/explosion.wav");
					explosion.play();
				}
			}
			currentShotX = TopLeftCellCorner.x + cellDimentions;
			currentShotY = TopLeftCellCorner.y + 12;
			dxshot = 0;
			dyshot = 0;
			return;
		}
		if (dxshot != 0) {
			currentShotX += dxshot;
			currentShotY += 0;
			drawHorizontalShot();
		}
	}
	
	if (up) {
		x1 = (currentShotX - 12) / cellDimentions;
		y1 = (currentShotY + dyshot) / cellDimentions;
		if (x1 == 0 && y1 == 1) {
			if ($("#enable-sound:checked").val() !== undefined) {
				victoryIsMine = new Audio("sound/victory.mp3");
				victoryIsMine.play();
			}
			endGame();
			restore();
			return;
		}
		if ((y1 % 1) == 0) {
			if (verti[y1 - 1][x1] != 1) wall = true;
		}
		clearVerticalShot();
		canvasEnd = (currentShotY - verticalShotHeight + dyshot) == 0;
		if (canvasEnd || wall) {
			if (wall && !canvasEnd) {
				verti[y1 - 1][x1] = 1;
				eraseHorizontalWall(x1,y1);
				if ($("#enable-sound:checked").val() !== undefined) {
					explosion = new Audio("sound/explosion.wav");
					explosion.play();
				}
			}
			currentShotX = TopLeftCellCorner.x + 12;
			currentShotY = TopLeftCellCorner.y - verticalShotHeight;
			dxshot = 0;
			dyshot = 0;
			return;
		}
		if (dyshot != 0) {
			currentShotX += 0;
			currentShotY += dyshot;
			drawVerticalShot();
		}
	}
	
	if (down) {
		x1 = (currentShotX - 12) / cellDimentions;
		y1 = (currentShotY + dyshot) / cellDimentions;
		if ((y1 % 1) == 0) {
			if (verti[y1 - 1][x1] != 1) wall = true;
		}
		clearVerticalShot();
		canvasEnd = (currentShotY + verticalShotHeight + dyshot) == canvas.height;
		if (canvasEnd || wall) {
			if (wall && !canvasEnd) {
				verti[y1 - 1][x1] = 1;
				eraseHorizontalWall(x1,y1);
				if ($("#enable-sound:checked").val() !== undefined) {
					explosion = new Audio("sound/explosion.wav");
					explosion.play();
				}
			}
			currentShotX = TopLeftCellCorner.x + 12;
			currentShotY = TopLeftCellCorner.y + cellDimentions;
			dxshot = 0;
			dyshot = 0;
			return;
		}
		if (dyshot != 0) {
			currentShotX += 0;
			currentShotY += dyshot;
			drawVerticalShot();
		}
	}
	}
}

// restore canvas and paramters to initial state.
// stop chase music if it is running.
function restore() {
	if (typeof(chase) != "undefined") {
		chase.pause();
		chase.setCurrentTime = 0;
	}
	initParameters();
	clearCanvas();
	drawGrid();
	drawLois();
}

function showRegisterForm(score) {
	var current_score = timeLeft;
	document.getElementById('register-form').style.visibility='visible';
	if (score == null) {
		$('#game_score').val(current_score);
		document.cookie = "tempScore=" + current_score;
	}
	else {
		$('#game_score').val(score);
		document.cookie = "tempScore=" + score;
	}
	$('#nickname_tb').val("");
	$('#email_tb').val("");
	$('#password_tb').val("");
	
}

function endGame() {
	var nickname = getCookie("nickname");
	if (nickname != null && nickname != "") {
		document.cookie = "tempScore=" + timeLeft;
		retrieveRecordsTable();
	}
	else {
		retrieveRecordsTable();
		showRegisterForm(null);
	}
	enable_scroll();
}

function retrieveRecordsTable() {
	$('#record_table_get_area').children().first().click();
}
